package com.example.managemyself.viewmodel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.managemyself.data.database.AppDatabase;
import com.example.managemyself.data.database.UserDao;
import com.example.managemyself.data.model.User;
import com.example.managemyself.model.UserSettings;
import com.example.managemyself.util.SettingsManager;
import com.example.managemyself.util.UserManager;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 个人资料ViewModel，处理用户资料相关的UI逻辑
 */
public class ProfileViewModel extends AndroidViewModel {
    
    private final MutableLiveData<Boolean> isLoading = new MutableLiveData<>(false);
    private final MutableLiveData<String> errorMessage = new MutableLiveData<>();
    private final UserDao userDao;
    private final ExecutorService executor;
    
    public ProfileViewModel(@NonNull Application application) {
        super(application);
        AppDatabase database = AppDatabase.getInstance(application);
        userDao = database.userDao();
        executor = Executors.newSingleThreadExecutor();
    }
    
    /**
     * 获取当前用户
     */
    public User getCurrentUser() {
        return UserManager.getInstance().getCurrentUser();
    }
    
    /**
     * 根据用户ID获取用户信息
     */
    public LiveData<User> getUser(int userId) {
        return userDao.getUserById(userId);
    }
    
    /**
     * 获取用户设置
     */
    public LiveData<UserSettings> getUserSettings(int userId) {
        return SettingsManager.getInstance().getUserSettings(userId);
    }
    
    /**
     * 更新用户设置
     */
    public void updateUserSettings(UserSettings settings) {
        SettingsManager.getInstance().updateUserSettings(settings);
    }
    
    /**
     * 保存用户设置
     */
    public void saveUserSettings(UserSettings settings) {
        SettingsManager.getInstance().updateUserSettings(settings);
    }
    
    /**
     * 更新用户信息
     */
    public LiveData<Boolean> updateUser(User user) {
        MutableLiveData<Boolean> result = new MutableLiveData<>();
        
        executor.execute(() -> {
            try {
                int rowsUpdated = userDao.updateUser(user);
                result.postValue(rowsUpdated > 0);
            } catch (Exception e) {
                result.postValue(false);
                errorMessage.postValue("更新用户信息失败: " + e.getMessage());
            }
        });
        
        return result;
    }
    
    /**
     * 更新用户资料
     */
    public void updateUserProfile(String username, String email, String avatar, UserProfileCallback callback) {
        isLoading.setValue(true);
        
        // TODO: 实现用户资料更新逻辑
        // 这里应该调用API更新用户资料
        
        // 模拟API调用
        new Thread(() -> {
            try {
                Thread.sleep(1000); // 模拟网络延迟
                
                // 模拟成功响应
                User currentUser = UserManager.getInstance().getCurrentUser();
                if (currentUser != null) {
                    currentUser.setUsername(username);
                    currentUser.setEmail(email);
                    currentUser.setAvatar(avatar);
                    
                    isLoading.postValue(false);
                    callback.onSuccess(currentUser);
                } else {
                    isLoading.postValue(false);
                    errorMessage.postValue("用户未登录");
                    callback.onError("用户未登录");
                }
            } catch (InterruptedException e) {
                isLoading.postValue(false);
                errorMessage.postValue("更新失败: " + e.getMessage());
                callback.onError("更新失败: " + e.getMessage());
            }
        }).start();
    }
    
    /**
     * 获取加载状态
     */
    public LiveData<Boolean> getIsLoading() {
        return isLoading;
    }
    
    /**
     * 获取错误信息
     */
    public LiveData<String> getErrorMessage() {
        return errorMessage;
    }
    
    /**
     * 用户资料更新回调接口
     */
    public interface UserProfileCallback {
        void onSuccess(User user);
        void onError(String error);
    }
} 